import React, { useEffect, useState } from "react";

import {
  Modal,
  Form,
  InputNumber,
  Table,
  Typography,
  Button,
  Input,
  Select,
} from "antd";
import { useDispatch } from "react-redux";
import {
  getroad,
  getsetroadadd,
} from "../../api/operation_maintenance/road_points";
import "./1.scss";

const App = () => {
  const [open, setOpen] = useState(false);
  const [data, setData] = useState([]);
  const showModal = (ref) => {
    llivbxc(false);
    setIsModalOpen(true);
  };
  const dispatch = useDispatch();

  const [aereewola, setaree] = useState({
    asidekind: "",
    nickname: "",
    kind: "",
    kind11: "",
  });
  const { Option } = Select;

  const [form] = Form.useForm();
  const onGenderChange = (value) => {
    switch (value) {
      case "male":
        form.setFieldsValue({
          note: "Hi, man!",
        });
        break;
      case "female":
        form.setFieldsValue({
          note: "Hi, lady!",
        });
        break;
      case "other":
        form.setFieldsValue({
          note: "Hi there!",
        });
        break;
      default:
    }
  };
  const onFinish = (values) => {
    console.log(values);
  };
  const onReset = () => {
    form.resetFields();
  };

  useEffect(() => {
    let obj = window.localStorage.getItem("useraa");
    console.log(obj);
    getroad().then((res) => {
      setData(res.data);
      dispatch({
        type: "attlist",
        payload: res.data,
      });
    });
  }, [dispatch]);

  function dsa() {
    let obj = JSON.parse(localStorage.getItem("data")) || [];
    console.log(obj, "----------------");

    setData(obj);
  }

  const handleOk = () => {
    dispatch({
      type: "add",
      payload: aereewola,
    });
    dsa();
    form.resetFields();

    setIsModalOpen(false);
  };
  //修改的函数
  const handleOk1 = (values) => {
    console.log(aereewola);
    //修改请求
    const data3 = JSON.parse(window.localStorage.getItem("dataee"));
    const data2 = { ...data3, ...aereewola };
    getsetroadadd(data2).then((res) => {
      setData(res.data);
    });
    setIsModalOpen(false);
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    const inputNode = inputType === "number" ? <InputNumber /> : <Input />;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[
              {
                required: true,
                message: `Please Input ${title}!`,
              },
            ]}
          >
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  const [editingKey, setEditingKey] = useState("");
  // 打开框状态
  const [isModalOpen, setIsModalOpen] = useState(false);

  const isEditing = (record) => record.key === editingKey;

  const cancel = () => {
    setEditingKey("");
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const [arrta, setlis] = useState({});

  const columns = [
    {
      title: "序号",
      render: function (text, record, index) {
        return <h3>{index + 1}</h3>;
      },
    },
    {
      title: "所在省份",
      dataIndex: "asidekind",
    },
    {
      title: "所在城市",
      dataIndex: "nickname",
    },
    {
      title: "所在县区",
      dataIndex: "kind",
    },
    {
      title: "道路站点名称",
      dataIndex: "kind11",
    },
    {
      title: "操作",
      dataIndex: "operation",
      render: (_, record) => {
        return (
          <>
            <Typography.Link
              onClick={() => {
                llivbxc(true);
                localStorage.setItem("dataee", JSON.stringify(record));
                console.log(record);
                setIsModalOpen(true);
              }}
            >
              调整
            </Typography.Link>

            <Typography.Link
              onClick={() => {
                console.log(data);

                window.localStorage.setItem("ooop", JSON.stringify(record));
             
                data.forEach((item, index) => {
                  if (item.id === record.id) {
                    data.splice(index, 1);
                    
                  }
                });
                setData([...data]);
              }}
              style={{ marginLeft: "10px", marginRight: "10px" }}
            >
              删除
            </Typography.Link>
            <Typography.Link
              onClick={() => {
                console.log(record);
                setOpen(true);
                setlis(record);
                window.localStorage.setItem("useraa", JSON.stringify(record));
                console.log(arrta);
              }}
            >
              查看
            </Typography.Link>
          </>
        );
      },
    },
  ];

  const [awwcb, llivbxc] = useState(false);

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === "age" ? "number" : "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  let obj = JSON.parse(window.localStorage.getItem("useraa"));

  return (
    <>
      <Form form={form} name="control-hooks" onFinish={onFinish}>
        <div className="left">
          <Form.Item
            name="note"
            label="道路站点名称"
            rules={[
              {
                required: false,
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="gender"
            label="所属区域"
            rules={[
              {
                required: false,
              },
            ]}
          >
            <Select
              placeholder="Select a option and change input text above"
              onChange={onGenderChange}
              allowClear
            >
              <Option value="male">male</Option>
              <Option value="female">female</Option>
              <Option value="other">other</Option>
            </Select>
            <Select
              placeholder="Select a option and change input text above"
              onChange={onGenderChange}
              allowClear
            >
              <Option value="male">male</Option>
              <Option value="female">female</Option>
              <Option value="other">other</Option>
            </Select>
            <Select
              placeholder="Select a option and change input text above"
              onChange={onGenderChange}
              allowClear
            >
              <Option value="male">male</Option>
              <Option value="female">female</Option>
              <Option value="other">other</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="gender"
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.gender !== currentValues.gender
            }
          >
            {({ getFieldValue }) =>
              getFieldValue("gender") === "other" ? (
                <Form.Item
                  name="customizeGender"
                  label="Customize Gender"
                  rules={[
                    {
                      required: false,
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
              ) : null
            }
          </Form.Item>
        </div>
        <div className="right">
          <Form.Item name="btn">
            <Button htmlType="button" onClick={onReset}>
              重置
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginLeft: "10px", marginRight: "10px" }}
            >
              查询
            </Button>

            <Button type="primary" onClick={showModal}>
              新增
            </Button>
          </Form.Item>
        </div>
      </Form>
      <Form form={form} component={false}>
        <Table
          rowKey="id"
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          bordered
          dataSource={data}
          columns={mergedColumns}
          rowClassName="editable-row"
          pagination={{
            onChange: cancel,
          }}
        />
      </Form>

      {/* //框 */}

      <Modal
        title={awwcb === false ? "新增" : "修改"}
        width={800}
        centered={false}
        className="los"
        open={isModalOpen}
        // onOk={}
        onOk={awwcb === false ? handleOk : handleOk1}
        onCancel={handleCancel}
      >
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="所在省份"
            name="asidekind"
            rules={[{ required: true, message: "Please input your key!" }]}
          >
            <Input
              value={aereewola.asidekind}
              onChange={(e) => {
                setaree({ ...aereewola, asidekind: e.target.value });
              }}
            />
          </Form.Item>

          <Form.Item
            label="所在城市"
            name="nickname"
            rules={[{ required: true, message: "Please input your name!" }]}
          >
            <Input
              value={aereewola.nickname}
              onChange={(e) => {
                setaree({ ...aereewola, nickname: e.target.value });
              }}
            />
          </Form.Item>

          <Form.Item
            label="所在县区"
            name="kind"
            rules={[{ required: true, message: "Please input your age!" }]}
          >
            <Input
              value={aereewola.kind}
              onChange={(e) => {
                setaree({ ...aereewola, kind: e.target.value });
              }}
            />
          </Form.Item>

          <Form.Item
            label="道路站点名称"
            name="kind11"
            rules={[{ required: true, message: "Please input your address!" }]}
          >
            <Input
              value={aereewola.kind11}
              onChange={(e) => {
                setaree({ ...aereewola, kind11: e.target.value });
              }}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 查看对话框 */}

      <Modal
        title="查看特殊车辆详情"
        centered
        open={open}
        onOk={() => setOpen(false)}
        onCancel={() => setOpen(false)}
        width={1700}
        className="aou"
      >
        <span>
          序号:<span>{obj.id}</span>
        </span>
        <span>
          所在省份:<span>{obj.asidekind}</span>
        </span>
        <span>
          所在城市:<span>{obj.nickname}</span>
        </span>
        <span>
          所在县区:<span>{obj.kind}</span>
        </span>
        <span>
          道路站点名称:<span>{obj.kind11}</span>
        </span>
        <span>
          城建时间:<span>{obj.time}</span>
        </span>
        <span>
          详细简介:<span>{obj.desc}</span>
        </span>
      </Modal>
    </>
  );
};

export default App;
